package com.jzo2o.foundations;

import cn.hutool.core.collection.CollUtil;
import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.model.dto.response.ServeCategoryResDTO;
import com.jzo2o.foundations.model.dto.response.ServeSimpleResDTO;
import com.jzo2o.foundations.service.HomeService;
import com.jzo2o.foundations.service.IRegionService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author itlxc
 * @since 2024-10-16
 */
@Slf4j
@RequiredArgsConstructor
public class ClearCacheTask {

    private final StringRedisTemplate redisTemplate;

    private final IRegionService regionService;

    private final HomeService homeService;

    @XxlJob("clearCacheHandler")
    public void clearCacheHandler() {
        log.info(">>>>>>> 开始定时清理缓存");
        // 删除缓存
        redisTemplate.delete(RedisConstants.CacheName.JZ_CACHE + "::ACTIVE_REGIONS");

        // 通过查询开通区域列表进行缓存
        List<RegionSimpleResDTO> regionSimpleResDTOS = regionService.queryActiveRegionList();

        // 遍历区域对该区域下的服务类型进行缓存
        regionSimpleResDTOS.forEach(item->{
            // 区域id
            Long regionId = item.getId();

            // 删除该区域下的首页服务列表
            String serve_type_key = RedisConstants.CacheName.SERVE_ICON + "::" + regionId;
            redisTemplate.delete(serve_type_key);
            List<ServeCategoryResDTO> list = homeService.queryServeIconCategoryByRegionIdCache(regionId);
            // 删除该区域下的服务类型列表缓存
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(dto -> {
                    List<ServeSimpleResDTO> serveResDTOList = dto.getServeResDTOList();
                    if (CollUtil.isEmpty(serveResDTOList)) {
                        return;
                    }
                    serveResDTOList.forEach(serveSimpleResDTO -> redisTemplate.delete(RedisConstants.CacheName.SERVE_TYPE + "::" + serveSimpleResDTO.getServeItemId()));
                });
            }
        });
        log.info(">>>>>>> 清理缓存完成");
    }
}
